from django.shortcuts import render, HttpResponse, render_to_response, redirect
from user.models import User, Admin
import os, dlib, glob, numpy, cv2
from skimage import io
import time
import urllib3, base64
from urllib.parse import urlencode
import requests
import re
from PIL import Image
import base64
from aip import AipFace

# Create your views here.
# 登录代码
m_data = ''


# 主页面
def index(request):
    if request.method == 'GET':
        return render(request, 'user/index.html')
    else:
        uname = request.POST.get('login_name').strip()
        upass = request.POST.get('login_pwd').strip()
        if uname == '' or upass == '':
            return render(request, 'user/index.html', {'err': '账号和密码都不能为空'})
        try:
            user = Admin.objects.get(admin=uname, adminpass=upass)
            if user:
                m_data = User.objects.all()
                return redirect('/menu')
        except:
            return render(request, 'user/index.html', {'err': '登录失败，请检查用户名或者密码'})


# 注册代码
def register(request):
    if request.method == 'GET':
        return render(request, 'user/register.html')
    else:
        uname = request.POST.get('userName').strip()
        upass = request.POST.get('password').strip()
        upass2 = request.POST.get('password2').strip()

        usf = request.POST.get('shenfen').strip()
    try:
        user = Admin()
        user.admin = uname
        user.adminnumber = usf
        if upass != upass2:
            return render(request, 'user/register.html', {'err1': '两次密码不一致'})
        else:
            user.adminpass = upass2
        user.save()
        return render(request, 'user/register.html', {'err2': '注册成功,返回去登录'})
    except:
        return render(request, 'user/register.html', {'err2': '用户名已被注册'})


# 跳转到展示界面
def menu(request):
    m_data = User.objects.all()
    return render(request, 'user/menu.html', {'m_data': m_data})


# 跳转到人脸对比网页
def face_pay(request):
    return render(request, 'user/face_pay.html')


# 用于接受前端发送过来的图片
def face(request):
    base64_1 = request.POST.get("base64_1")
    imgdata = base64.b64decode(base64_1)
    file = open('1.jpg', 'wb')
    file.write(imgdata)
    file.close()
    zhi = faceduibi()
    if zhi == 1:
        return HttpResponse(1)
    elif zhi == 0:
        return HttpResponse(0)
    else:
        return HttpResponse('未识别到人脸')


# 支付成功页面
def succeed(request):
    return render(request, 'user/succeed.html')


def up_img(request):
    id = request.POST.get("id")
    img = request.POST.get("img_data")
    # print('id', id)
    # print('img', img)
    # print('*' * 100)
    # print(type(img))

    user = User.objects.get(id=id)
    user.userimg = "data:image/jpeg;base64," + img
    user.save()



    return HttpResponse('ok')


# 人脸对比主要函数
def faceduibi():
    print(time.time())
    predictor_path = 'shape_predictor_68_face_landmarks.dat'
    # 2.人脸识别模型
    # face_rec_model_path = sys.argv[2]
    face_rec_model_path = 'dlib_face_recognition_resnet_model_v1.dat'
    # 3.候选人脸文件夹
    # faces_folder_path = sys.argv[3]
    faces_folder_path = './girls'
    # 4.需识别的人脸
    # img_path = sys.argv[4]
    img_path = "1.jpg"
    # 1.加载正脸检测器
    detector = dlib.get_frontal_face_detector()
    # 2.加载人脸关键点检测器
    sp = dlib.shape_predictor(predictor_path)
    # 3. 加载人脸识别模型
    facerec = dlib.face_recognition_model_v1(face_rec_model_path)

    # win = dlib.image_window()
    # 候选人脸描述子list
    descriptors = []
    candidate = []
    # 对文件夹下的每一个人脸进行:
    # 1.人脸检测
    # 2.关键点检测
    # 3.描述子提取

    # for f in glob.glob(os.path.join(faces_folder_path, "*.jpg")):
    #     # print("Processing file: {}".format(f))
    #     file1 = f.split("\\")
    #     filename = file1[1].split(".")
    #     candidate.append(filename[0])
    #     img = io.imread(f)
    #     # win.clear_overlay()
    #     # win.set_image(img)
    #
    #     # 1.人脸检测
    #     dets = detector(img, 1)
    #     print('===========')
    #     # print("Number of faces detected: {}".format(len(dets)))
    #     for k, d in enumerate(dets):
    #         # 2.关键点检测
    #         shape = sp(img, d)
    #         # 画出人脸区域和和关键点
    #         # win.clear_overlay()
    #         # win.add_overlay(d)
    #         # win.add_overlay(shape)
    #         # 3.描述子提取，128D向量
    #         face_descriptor = facerec.compute_face_descriptor(img, shape)
    #         # 转换为numpy array
    #         v = numpy.array(face_descriptor)
    #         print('----')
    #         descriptors.append(v)
    #
    # numpy.save('desc_file.npy', descriptors)
    # numpy.save('candidate_file.npy', candidate)
    # print(candidate)
    # 对需识别人脸进行同样处理
    # 提取描述子，不再注释

    descriptor = numpy.load("desc_file.npy")
    candidate = numpy.load("candidate_file.npy")
    for i in descriptor:
        array = numpy.array(i)
        descriptors.append(array)
    print(descriptors)
    dist = []

    img = io.imread(img_path)[:, :, :3]

    dets = detector(img, 1)
    for k, d in enumerate(dets):
        shape = sp(img, d)
        face_descriptor = facerec.compute_face_descriptor(img, shape)
        d_test = numpy.array(face_descriptor)

        # 计算欧式距离
        for i in descriptors:
            dist_ = numpy.linalg.norm(i - d_test)
            dist.append(dist_)

    # 候选人名单

    # 候选人和距离组成一个dict
    c_d = dict(zip(candidate, dist))
    cd_sorted = sorted(c_d.items(), key=lambda d: d[1])
    # print(cd_sorted)
    print(time.time())
    if (len(cd_sorted)):

        if (cd_sorted[0][1] < 0.45):
            print('\n The person is: %s' % (cd_sorted[0][0]))
            print(cd_sorted[0][1])
            return 1
        else:
            # print("\n-----暂无此人信息")
            return 0
    else:
        # print("\n未识别到人脸")
        return '未识别到人脸'

    dlib.hit_enter_to_continue()


# 用于跳转到添加页面
def addin(request):
    return render(request, 'user/add.html')


# 用于接受要添加的数据
def addout(request):
    if request.method == "GET":
        return render(request, 'user/add.html')
    else:
        username = request.POST.get('username').strip()
        userpass = request.POST.get('userpass').strip()
        useremail = request.POST.get('useremail').strip()
        uname = request.POST.get('uname').strip()
        usernumber = request.POST.get('usernumber').strip()
        userimg = request.POST.get('img')


        if username == '':
            return render(request, 'user/add.html', {'usname': '用户名不能为空'})
        if userpass == '':
            return render(request, 'user/add.html', {'uspass': '密码不能为空'})
        if useremail == '':
            return render(request, 'user/add.html', {'usemail': '邮箱不能为空'})
        if uname == '':
            return render(request, 'user/add.html', {'uname': '姓名不能为空'})
        if usernumber == '':
            return render(request, 'user/add.html', {'usnumber': '身份证不能为空'})
        if userimg == '':
            return render(request, 'user/add.html', {'img': '还没有上传图片'})


        try:
            User.objects.get(username=username)

        except Exception:
            User.objects.create(username=username, userpass=userpass, useremail=useremail, uname=uname,
                                usernumber=usernumber,userimg=userimg)

            return redirect('/menu')

        return render(request, 'user/add.html', {'usname': '用户名已被注册'})


# 删除单条数据
def del_(request):
    id = request.POST.get("id")
    u = User.objects.get(id=id)
    u.delete()
    return redirect('/menu')


u = ''
uid = ''


# 用于跳转到修改页面
def updetin(request):
    global u, uid;
    uid = request.GET.get("id")
    u = User.objects.get(id=uid)
    return render(request, 'user/updet.html', {'user': u})


# 接受修改后的数据
def updetout(request):
    print(uid)
    usname = request.POST.get('username')
    uspass = request.POST.get('userpass')
    usemail = request.POST.get('useremail')
    un = request.POST.get('uname')
    usnumber = request.POST.get('usernumber')
    if uspass == '':
        return render(request, 'user/updet.html', {'user': u, 'us': '密码不能为空'})
    if usemail == '':
        return render(request, 'user/updet.html', {'us': '邮箱不能为空', 'user': u})
    if un == '':
        return render(request, 'user/updet.html', {'us': '姓名不能为空', 'user': u})
    if usnumber == '':
        return render(request, 'user/updet.html', {'us': '身份证不能为空', 'user': u})

    User.objects.filter(id=int(uid)).update(username=usname, userpass=uspass, useremail=usemail, uname=un,
                                            usernumber=usnumber)

    return redirect('/menu')


def face_analyze(request):
    return render(request,'user/face_analyze.html')

# 用于接受前端发送过来的图片
def face1(request):
    base64_11 = request.POST.get("base64_11")
    imgdata1 = base64.b64decode(base64_11)
    file = open('2.jpg', 'wb')
    file.write(imgdata1)
    #file.close()

    zhi1 = shibe()
    return HttpResponse(zhi1)

#人脸表情识别
def shibe():
    """ 你的 APPID AK SK """
    APP_ID = '14874519'# 你的 App ID
    API_KEY = 'T5cwSFY5bPOfOGEXMFMy2Rt6'  # 你的 Api Key’
    SECRET_KEY = 'bvvgT8LXjG79NOIleaPFx7ODy60Vc02c'  # 你的 Secret Key
    client = AipFace(APP_ID, API_KEY, SECRET_KEY)

    with open('2.jpg', "rb") as f:
        data = f.read()
    # data='2.jpg'
    encodestr = base64.b64encode(data)  # 得到 byte 编码的数据
    images = str(encodestr, 'utf-8')  # 重新编码数据
    image = images
    imageType = "BASE64"

    """ 调用人脸检测 """
    # m = client.detect(image, imageType)
    # print(m)
    """ 如果有可选参数 """
    options = {}
    options["max_face_num"] = 10
    options["face_field"] = "age,beauty,expression,face_shape,gender,glasses,emotion"

    """ 带参数调用人脸检测 """
    m = client.detect(image, imageType, options)
    if m["error_msg"] == "SUCCESS":
        mm = m["result"]
        #print(mm)
        num = mm["face_num"]
        #print("num",num)
        for i in range(num):
            mmm = mm["face_list"][i]
            age = mmm["age"]
            beauty = mmm["beauty"]
            # 表情
            exp = {'none': "不笑", 'smile': "微笑", 'laugh': "大笑"}
            expression = mmm["expression"]['type']
            if expression in exp:
                expressions = exp[expression]
            else:
                expressions = "未知"

            # # 脸型
            # face = {'square': '正方形', 'triangle': '三角形', 'oval': '椭圆', 'heart': '心形', 'round': '圆形'}
            # face_shape = mmm["face_shape"]['type']
            # if face_shape in face:
            #     face_shapes = face[face_shape]
            # else:
            #     face_shapes = "未知"

            # 性别
            gen = {'male': '男', 'female': '女'}
            gender = mmm["gender"]['type']
            if gender in gen:
                genders = gen[gender]
            else:
                genders = "未知"

            # 情绪
            emo = {'angry': '愤怒', 'disgust': '厌恶', 'fear': '恐惧', 'happy': '高兴', 'sad': '伤心', 'surprise': '惊讶',
                   'neutral': '无情绪'}
            emotion = mmm["emotion"]['type']
            if emotion in emo:
                emotions = emo[emotion]
            else:
                emotions = "未知"

            return ("人脸数：%d, 年龄：%d, 颜值：%d, 表情：%s, 性别：%s, 情绪：%s"
                  % (num,age, beauty, expressions, genders, emotions))
            # return ("人脸数：%s, 年龄：%s, 颜值：%s, 表情：%s, 性别：%s, 情绪：%s"
            #         % (list1,list2,list3,list4,list5,list6))
